package cn.tedu.ximart.server.filter;

import cn.tedu.ximart.server.security.LoginPrincipal;
import cn.tedu.ximart.server.utils.JwtUtils;
import cn.tedu.ximart.server.web.JsonResult;
import cn.tedu.ximart.server.web.ServiceCode;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {


    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {
        log.debug("执行JwtAuthenticationFilter");

        //清除客户端缓存的上下文里的信息
        SecurityContextHolder.clearContext();

        //从请求头中获取JWT
        String jwt = request.getHeader("Authorization");
        log.debug("从请求头中获取的JWT数据：{}", jwt);

        //先判断是否获取到了有效的JWT值，则尝试进行解析
        if (!StringUtils.hasText(jwt)) {
            log.debug("请求头中的JWT数据是无效的，直接放行");
            filterChain.doFilter(request, response);
            return;
        }

        //如果获取到了有效的JWT值，则尝试进行解析
        Claims claims = null;
        try {
            claims = JwtUtils.parse(jwt);
        } catch (ExpiredJwtException e) {
            log.debug("解析JWT失败，JWT过期：{}, {}", e.getClass().getName(), e.getMessage());
            String errorMessage = "登录信息已过期，请重新登录！";
            JsonResult jsonResult = JsonResult.fail(ServiceCode.ERR_JWT_EXPIRED, errorMessage);
            String jsonResultString = JSON.toJSONString(jsonResult);
            log.debug("将向客户端响应：{}", jsonResultString);
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().println(jsonResultString);
            return;
        } catch (SignatureException e) {
            log.debug("解析JWT失败，签名错误：{}, {}", e.getClass().getName(), e.getMessage());
            String errorMessage = "获取登录信息失败，请重新登录！";
            JsonResult jsonResult = JsonResult.fail(ServiceCode.ERR_JWT_INVALID, errorMessage);
            String jsonResultString = JSON.toJSONString(jsonResult);
            log.debug("将向客户端响应：{}", jsonResultString);
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().println(jsonResultString);
            return;
        } catch (MalformedJwtException e) {
            log.debug("解析JWT失败，JWT数据有误：{}, {}", e.getClass().getName(), e.getMessage());
            String errorMessage = "获取登录信息失败，请重新登录！";
            JsonResult jsonResult = JsonResult.fail(ServiceCode.ERR_JWT_INVALID, errorMessage);
            String jsonResultString = JSON.toJSONString(jsonResult);
            log.debug("将向客户端响应：{}", jsonResultString);
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().println(jsonResultString);
            return;
        } catch (Throwable e) {
            log.debug("解析JWT失败，错误详情：{}, {}", e.getClass().getName(), e.getMessage());
            String errorMessage = "获取登录信息失败，请重新登录！";
            JsonResult jsonResult = JsonResult.fail(ServiceCode.ERR_JWT_INVALID, errorMessage);
            String jsonResultString = JSON.toJSONString(jsonResult);
            log.debug("将向客户端响应：{}", jsonResultString);
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().println(jsonResultString);
            return;
        }

        //从解析JWT的结果中取出登录的管理员信息
        Object id = claims.get("id");
        Object username = claims.get("username");
        Object authoritiesString = claims.get("authorities");
        log.debug("从JWT中解析到的信息为：{}，{}，{}", id, username, authoritiesString);

        //将从JWT中解析得到的权限列表的字符串封装为GrantedAuthority集合中
        List<SimpleGrantedAuthority> authorities = JSON.parseArray(authoritiesString.toString(), SimpleGrantedAuthority.class);
        //准备当前登录用户的当事人信息
        LoginPrincipal loginPrincipal = new LoginPrincipal();
        loginPrincipal.setId(Long.parseLong(id.toString()));
        loginPrincipal.setUsername(username.toString());

        //当解析成功后，应该将Authentication存入到Spring Security的上下文中
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                loginPrincipal, null, authorities);
        SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(authentication);
        log.debug("已经向Security的上下文中存入信息：{}", authentication);

        //以下代码将执行放行
        filterChain.doFilter(request, response);
    }
}
